<?php

namespace backend\models\rbac;

use Yii;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;


class AuthAssignment extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%auth_assignment}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
        ];
    }

    /**
     * @param $q
     * @param string $role
     * @return array|ActiveRecord[]
     */
    public function getList($q, $role='') {
        $query = $this->find();
        return $query->from(self::tableName() ." as t1")
                    ->leftJoin('sale_user as t2', 't2.id = t1.user_id')
                    ->select('t2.id,t2.name, t2.account, t2.phone')
                    ->where(['like', 't2.name', $q])
                    ->andFilterWhere(['t1.item_name' => $role])
                    ->distinct()
                    ->orderBy('t2.id asc')
                    ->asArray()
                    ->all();
    }

    public function add($name,$id){
        $authManager = Yii::$app->authManager;
        $value = $authManager->getRole($name);
        if($value==''){
            return false;
        }
        $item = $authManager->getRole($name);
        $item = $item ? : $authManager->getPermission($name);
        $authManager->assign($item, $id);
        return true;
    }

    public static function getRoles(){
        $roles = AuthAssignment::find()->select('item_name')->where('user_id=:UID',[':UID'=>Yii::$app->user->identity->id])->asArray()->all();
        if(!empty($roles)){
            $roles = ArrayHelper::getColumn($roles, 'item_name');
            return $roles;
        }else{
            return array();
        }
    }

}
